
const { app, BrowserWindow, ipcMain } = require('electron/main');
const path = require('node:path');
const ffi = require('ffi-napi');
const ref = require('ref-napi');
const fs = require('fs')

let nfcDr;
try {
  nfcDr = new ffi.Library("./NFCCARD64.dll", {
    callnfc: [
      'string',
      ['string', 'pointer', 'pointer'],
      'stdcall'
    ],
    initDevice: [
      'string',
      []
    ]
  });
} catch (e) {
  console.error('DLL LoadError:', e);
  return;
}

const Dll_write = (_, data) => {

  const outputBuffer = Buffer.alloc(1024);

  const outputLengthPtr = ref.alloc('ushort');

  const result = nfcDr.callnfc(
    data,
    outputBuffer,
    outputLengthPtr
  );

  console.log('result:', result);
  return result;

}

function createWindow() {
  nfcDr.initDevice()

  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile("./index.html");
}

app.whenReady().then(() => {

  ipcMain.handle('writeConfig', (event, params) => {
    return writeConfig(event, params);
  });

  ipcMain.handle('Dll_write', (event, data) => {
    return Dll_write(event, data);
  })

  ipcMain.handle('readConfig', readConfig)
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});


const configPath = path.join(__dirname, '../Hotelconfig.json');

function writeConfig(_, config) {
  try {
    // 确保目录存在
    const dir = path.dirname(configPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`chuangjian : ${dir}`);
    }

    const jsonData = JSON.stringify(config, null, 2);
    fs.writeFileSync(configPath, jsonData);
    console.log(`Write success: ${configPath}`);
    return true;
  } catch (err) {
    console.error(`Error ${configPath} :`, err);
    return false;
  }
}

function readConfig() {
  console.log(`readConfig: ${configPath}`);
  try {
    if (!fs.existsSync(configPath)) {
      console.warn(`read error: ${configPath}`);
      return null;
    }

    const data = fs.readFileSync(configPath, 'utf8');

    console.log(`Read success: ${data}`);
    return JSON.parse(data);
  } catch (err) {
    console.error(`Error1 ${configPath} :`, err);
    return null;
  }
} 